<?php
set_time_limit(60);
date_default_timezone_set('PRC');
require_once(dirname(__FILE__).'/../lib/Comm.class.php');
require_once(dirname(__FILE__).'/../lib/Crawler.class.php');

class CrawlRecord
{
    public static function run($dorm, $start, $end, $type)
    {
        echo date('Y-m-d H:i:s')."  dorm: ".$dorm." start: ".$start." end: ".$end." type: ".$type."\n";
        $t_start = $start;
        while(Comm::dateCount($t_start, $end) >= 0)
        {
            $t_end = date('Y-m-d', strtotime($t_start." +9 days"));
            $d = Comm::dateCount($t_end, $end);
            if($d < 0) { $t_end = $end; $d = 0; }
            self::crawl($dorm, $t_start, $t_end, $type);
            $t_start = date('Y-m-d', strtotime($t_end." +1 days"));
        }
        return true;
    }

    public static function crawl($dorm, $start, $end, $type=2)
    {
        //echo $start." to ".$end."\n"; // do work
        $obj = new Crawler();
        $obj->elecLogin($dorm, $type);
        $info = $obj->queryRecord($start, $end);
        $db = Comm::connDb();
        if(!empty($info['overview']))
        {
            $sql = sprintf("INSERT INTO overview (dorm, total) VALUES ('%s', %f)". 
                "ON DUPLICATE KEY UPDATE total=VALUES(total);", $dorm, 
                floatval($info['overview'][0]));
            $db->exec($sql);
        }
        $cnt = count($info['time']);
        if(isset($info['used']))
            $sql = "INSERT IGNORE INTO used(dorm, time, cost) VALUES ";
        else
            $sql = "INSERT IGNORE INTO buy(dorm, time, amount, advance, channel) VALUES ";
        for($i = $cnt - 1; $i >= 0; $i--)
        {
            if($i != ($cnt - 1)) $sql .= ', ';
            if(isset($info['used']))
            {
                $sql .= sprintf("('%s', '%s', %f)", $dorm, 
                        $info['time'][$i], floatval($info['cost'][$i]));
            }
            else if(isset($info['buy']))
            {
                $sql .= sprintf("('%s', '%s', %f, %f, '%s')",  $dorm, $info['time'][$i], 
                    floatval($info['amount'][$i]), floatval($info['advance'][$i]), 
                    $info['channel'][$i]);
            } 
        }
        if($cnt != 0)
        {
            $sql .= ';';
            $result = $db->exec($sql);
        }
    }
}

// ---------------run-------------------

if(isset($argv[1]) && $argv[1] != 'CrawlRecord')
{
    $arr = Comm::s2a($argv[1]);
    if(empty($arr['dorm']) || empty($arr['start']) || empty($arr['end']) || empty($arr['type']))
    {
        echo 'error param';
        exit;
    }
    if($arr['type'] == 'used') $type = 2; else $type = 1;
    CrawlRecord::run($arr['dorm'], $arr['start'], $arr['end'], $type);
}
else
    echo '带参数运行';
exit;
?>
